package com.stony.controller;

import com.alibaba.fastjson.JSON;
import com.stony.comm.MediaTypes;
import com.stony.model.HostModel;
import com.stony.model.UserModel;
import com.stony.service.HostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/")
public class MainController {

    Logger log = LoggerFactory.getLogger(MainController.class);

    @Resource
    public HostService hostService;



	@RequestMapping(method = RequestMethod.GET)
	public String index(ModelMap model, HttpServletRequest request) {
        model.addAttribute("hosts", hostService.getHosts());
        model.addAttribute("path", request.getContextPath());

		return "index";
	}
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public String page(ModelMap model, HttpServletRequest request) {
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("hosts", hostService.getHosts());
        return "mongo/page";
    }


    @RequestMapping(value = "/coll/{id}/{name}")
    public String coll(ModelMap model, @PathVariable int id, @PathVariable String name, HttpServletRequest request) {
        log.debug("coll id : {}", id);
        HostModel host = hostService.getHost(id);
        Map data = hostService.getCollInfos(host.getHost(), host.getPort(), name);
        model.addAttribute("collInfos", data);
        model.addAttribute("datastr", JSON.toJSON(data));
        model.addAttribute("id", id);
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("name", name);
        model.addAttribute("server", (host.getHost() + ":" + host.getPort()));
        return "mongo/collinfo";
    }

    /**
     *
     * @param model
     * @param id host id
     * @param name database name
     * @param request
     * @return
     */
    @RequestMapping(value = "/database/{id}/{name}")
    public String database(ModelMap model, @PathVariable int id, @PathVariable String name, HttpServletRequest request) {
        log.debug("get database id : {}, name : {}", id, name);
        HostModel host = hostService.getHost(id);
        Map data = hostService.getDBAllInfos(host.getHost(), host.getPort());
        model.addAttribute("collInfos", ((Map)data.get(name)).get("coll_stats"));
        model.addAttribute("datastr", JSON.toJSON(((Map)data.get(name)).get("coll_stats")));
        model.addAttribute("dbInfos", data);
        model.addAttribute("id", id);
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("name", name);
        model.addAttribute("server", (host.getHost() + ":" + host.getPort()));
        return "mongo/database";
    }

    /**
     *
     * @param model
     * @param id host id
     * @param name database name
     * @param coll collection name
     * @param request
     * @return
     */
    @RequestMapping(value = "/database/{id}/{name}/{coll:.*}")
    public String collection(ModelMap model, @PathVariable int id, @PathVariable String name, @PathVariable String coll, HttpServletRequest request) {
        log.debug("get collection id : {}, name : {}, coll : {}", id, name, coll);
        HostModel host = hostService.getHost(id);
        Map data = hostService.getDBAllInfos(host.getHost(), host.getPort());
        Set<String> columns = hostService.getColumns(host,name,coll);
        model.addAttribute("collInfos", ((Map)data.get(name)).get("coll_stats"));
        model.addAttribute("dbInfos", data);
        model.addAttribute("path", request.getContextPath());
        model.addAttribute("id", id);
        model.addAttribute("name", name);
        model.addAttribute("coll", coll);
        model.addAttribute("server", (host.getHost() + ":" + host.getPort()));
        model.addAttribute("columns", columns);
        return "mongo/collection";
    }

    @RequestMapping(value = "/map/{id}", method = RequestMethod.GET)
    public String map(ModelMap model, @PathVariable int id, HttpServletRequest request) {
        log.debug("map database get : {}", id);
        model.addAttribute("path", request.getContextPath());
        HostModel host = hostService.getHost(id);
        model.addAttribute("infos", JSON.toJSON(hostService.getProvinceCount(host)));
        return "mongo/map";
    }



    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap model, HttpServletRequest request) {
        model.addAttribute("path", request.getContextPath());
        return "login";
    }


    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaTypes.JSON)
    public Object login(ModelMap model,
                            HttpServletRequest request,
                            HttpSession session,
                            @RequestParam(required = false) String remember,
                            @RequestParam String username,
                            @RequestParam String password) {
//        model.addAttribute("path", request.getContextPath());
        log.debug("login username : {}, password : {}", username, password);
        Map data = new HashMap();
        UserModel user = hostService.getUser(new UserModel(username, password));

        if(user != null){
            session.setAttribute("user", user);
            data.put("status", "OK");
            data.put("msg", "OK");
        }else{
            data.put("status", "FAIL");
            data.put("msg", "用户名密码错误！");
        }
        return data;
    }


    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(ModelMap model, HttpServletRequest request) {
        model.addAttribute("path", request.getContextPath());
        return "register";
    }


    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Object register(ModelMap model, HttpServletRequest request,
                           @RequestParam String email,
                           @RequestParam String password,
                           @RequestParam String password_again,
                           @RequestParam(required = false) String agree) {
        if(hostService.addUser(email, password)){
            return "redirect:" + request.getContextPath();
        }else{
            model.addAttribute("path", request.getContextPath());
            return "register";
        }
    }


    @ResponseBody
    @RequestMapping(value = "/forgot", method = RequestMethod.POST)
    public Object forgot(ModelMap model, HttpServletRequest request) {
        model.addAttribute("path", request.getContextPath());
        Map data = new HashMap();
        return data;
    }

}